/**
 * @this 顶部横滚动 ，并不会出现一半的情况 (主要解决小屏显示问题)
 *
 * @flow
 */

'use strict'
import React, {Component} from 'react'
// prettier-ignore
import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  TouchableOpacity,
} from 'react-native'

import PropTypes from 'prop-types'

import LocationUtil from '../../commons/utils/LocationUtil'
import RxColors from '../../commons/styles/RxColors'
/**
 * @RxScrollBar 顶部横滚动
 * @param barsText {array}
 */
export default class RxScrollBar extends Component {
  static propTypes = {
    ...ScrollView.propTypes,
    barsText: PropTypes.arrayOf(PropTypes.string),
    selectIndex: PropTypes.number,
    onPress: PropTypes.func,
  }

  static defaultProps = {
    ...ScrollView.defaultProps,
    selectIndex: 0,
    onPress: () => {},
  }

  constructor(props) {
    super(props)
    this.state = {
      selectIndex: 0,
      width: 0,
    }
    this.barrier = false
    this.itemsMeasure = []
    this.contentMeasure = 0
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (this.props != nextProps) {
      this.state.barrier = false
      this.renderDone(nextProps)
    }
  }

  renderDone = (props = this.props) => {
    const barrier = this.state.barrier
    if (barrier) return true
    let {barsText} = props
    barsText = barsText || []
    if (this.contentMeasure && this.itemsMeasure.length === barsText.length) {
      this.scrollToCenter(props)
      return true
    }
    return false
  }

  scrollToCenter = nextProps => {
    let {selectIndex, barsText} = nextProps
    if (!barsText) return
    barsText = barsText || []
    if (barsText.length === 0) return
    if (selectIndex !== this.state.selectIndex && selectIndex < barsText.length) {
      this.state.selectIndex = selectIndex
      if (this.refScrollView && this.refScrollView.scrollTo) {
        let offsetX = 0
        const lastMeasure = this.itemsMeasure[selectIndex]
        const lastLeft = lastMeasure.x || 0
        var lastWidth = lastMeasure.width || 0
        lastWidth = Math.floor(lastWidth / 2) + lastLeft + 4
        const contentWidth = this.refScrollView.width || 0
        console.log('refScrollView=', this.refScrollView)
        console.log('contentWidth=', contentWidth)
        const centerX = Math.floor(contentWidth / 2)
        if (lastWidth > centerX) {
          offsetX = lastWidth - centerX
          if (offsetX + contentWidth > this.contentMeasure) {
            offsetX = this.contentMeasure - contentWidth
          }
        }
        this.refScrollView.scrollTo({x: offsetX, y: 0, animal: true})
      }
    }
  }

  renderItem = () => {
    let {barsText, selectIndex, onPress} = this.props
    barsText = barsText || []
    let bts = []
    for (let i = 0; i < barsText.length; i++) {
      const txt = barsText[i]
      let fontColor = null
      if (i === selectIndex) {
        fontColor = {color: RxColors.BtnBlue}
      }
      const view = (
        <TouchableOpacity
          key={'scroll_bar_item_' + i}
          style={styles.region}
          activeOpacity={1}
          onPress={() => {
            if (i !== selectIndex) {
              onPress && onPress(i)
            }
          }}
          ref={e => {
            if (!e) return
            LocationUtil.relativeLocation(e, measure => {
              if (
                measure.x !== 0 ||
                measure.y !== 0 ||
                measure.width !== 0 ||
                measure.height !== 0
              ) {
                const itemLength = this.itemsMeasure.length
                if (i >= itemLength) {
                  this.itemsMeasure.push(measure)
                } else {
                  this.itemsMeasure[i] = measure
                }
                this.renderDone()
              }
            })
          }}>
          <Text style={[styles.text, fontColor]}>{txt}</Text>
        </TouchableOpacity>
      )
      bts.push(view)
    }
    return bts
  }

  render() {
    return (
      <View style={styles.container}>
        <ScrollView
          ref={e => {
            this.refScrollView = e
          }}
          style={{flex: 1}}
          decelerationRate={0.4}
          scrollEventThrottle={30}
          horizontal={true} // 横向
          showsVerticalScrollIndicator={false}
          showsHorizontalScrollIndicator={false}
          bounces={false}
          snapToInterval={74 + 20}
          snapToAlignment={'center'}>
          <View
            style={styles.scrollViewContent}
            ref={e => {
              if (!e) return
              LocationUtil.relativeLocation(e, measure => {
                if (
                  measure.x !== 0 ||
                  measure.y !== 0 ||
                  measure.width !== 0 ||
                  measure.height !== 0
                ) {
                  this.contentMeasure = measure.width
                  this.renderDone()
                }
              })
            }}>
            {this.renderItem()}
          </View>
        </ScrollView>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    height: 47,
    // backgroundColor: RxColors.White,
  },
  scrollViewContent: {
    flexDirection: 'row',
    paddingLeft: 4,
    paddingRight: 4,
  },
  region: {
    height: 46,
    justifyContent: 'center',
    alignItems: 'center',
  },
  text: {
    paddingLeft: 16,
    paddingRight: 16,
    textAlign: 'center',
    fontSize: 14,
    // color: RxColors.TextLightGray,
    color: RxColors.White,
    minWidth: 72,
  },
})
